package com.em.controller;

import com.em.entity.User;
import com.em.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Collections;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {
    private static String PAGE = "/user";
    private static String REDIRECT_PAGE = "redirect:" + PAGE;

    @Autowired
    private UserService userService;

    @GetMapping("/list")
    public String userList(@RequestParam(value = "username", defaultValue = "") String username,
                           @RequestParam(value = "page", defaultValue = "1") int pageNumber,
                           Model model) {
        int pageSize = 10; // 每页显示10个用户
        List<User> userList = userService.selectByUsername(username);
        int totalSize = userList.size();
        int start = (pageNumber - 1) * pageSize;
        // 确保start不超过userList的大小
        if (start > totalSize) {
            userList = Collections.emptyList(); // 如果超出范围，返回空列表
        } else {
            // 获取分页数据
            userList = userList.subList(start, Math.min(start + pageSize, totalSize));
        }
        model.addAttribute("list", userList);
        model.addAttribute("pageNumber", pageNumber);
        model.addAttribute("totalPages", userList.size());
        return PAGE + "/list";
    }

    @PostMapping("/add")
    public String add(@RequestParam(value = "username") String username,
                      @RequestParam(value = "username") String password,
                      @RequestParam(value = "type", required = false) String type) {
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        userService.createUser(user);
        return REDIRECT_PAGE + "/list";
    }

    @PostMapping("/edit")
    public String edit(@RequestParam(value = "id") Integer id,
                         @RequestParam(value = "username") String username) {
        User user = new User();
        user.setId(id);
        user.setUsername(username);
        userService.updateUser(user);
        return REDIRECT_PAGE + "/list";
    }


    @GetMapping("/delete")
    public String deleteUser(@RequestParam("id") Integer id) {
        userService.deleteUser(id);
        return REDIRECT_PAGE + "/list";
    }
}
